package com.sk.bilibili.event;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.context.ApplicationEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 邵康
 * @date 2021/12/15 8:29
 */
@Getter
@ToString
public class BiliBiliEvent<T> extends ApplicationEvent {

    private String type;
    private T data;
    private Map<String,Object> extra;

    public BiliBiliEvent(Object source) {
        this(source,null);
    }

    public BiliBiliEvent(Object source, T data) {
        super(source);
        this.data = data;
        extra=new HashMap<>();
        initType();
    }

    public BiliBiliEvent<T> putExtra(String key, Object value){
        extra.put(key,value);
        return this;
    }

    public <D> D getExtra(String key){
        return (D) extra.get(key);
    }

    private void initType() {
        StackTraceElement[] elements = Thread.currentThread().getStackTrace();
        String name = source.getClass().getName();
        for (StackTraceElement element : elements) {
            if(element.getClassName().equals(name)){
                type=name+"."+element.getMethodName();
                return;
            }
        }
        throw new RuntimeException("初始化Type失败:"+toString());
    }

}
